package com.changhongit.order.service;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.changhongit.order.entity.MaterialDetailEntity;
import com.changhongit.order.model.MaterailReq;

@Service
@SuppressWarnings("all")
public class InvoceJdbcService {

	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private EntityManager entityManager;

	public List<MaterialDetailEntity> findRule(MaterailReq materailReq) {
		List<MaterialDetailEntity> list = null;
		try {
			  StringBuffer buff =new StringBuffer("SELECT " + 
						"po_header_id," + 
						"po_number," + 
						"org_name," + 
						"vendor_name," + 
						"line_number," + 
						"item_name," + 
						"unit_meas_lookup_code," + 
						"quantity," + 
						"unit_price_tax," + 
						"unit_price," + 
						"amount_tax," + 
						"flye," + 
						"amount," + 
						"tax_rate," + 
						"cs_po," + 
						"fl_use_amount" + 
						" FROM " + 
						"kududb.kudu_cux_po_invoice_detail t" + 
						" WHERE " + 
						"( ( t.pll_quantity_received <> '0' AND t.pl_close_code = 'CLOSED' ) OR COALESCE ( t.pl_close_code, '空' ) <> 'CLOSED' ) ");
		  
			if (!StringUtils.isEmpty(materailReq.getSupplier())) {
				buff.append(" AND translate ( translate ( vendor_name, '(', '（' ), ')', '）' ) = '" + materailReq.getSupplier() + "'");
			}
			if (!StringUtils.isEmpty(materailReq.getOu())) {
				buff.append(" AND org_name = '" + materailReq.getOu() + "'");
			}
			if (!StringUtils.isEmpty(materailReq.getTax())) {
				buff.append(" AND tax_rate = " + materailReq.getTax());
			}
			if (!StringUtils.isEmpty(materailReq.getMaterial())) {
				buff.append(" AND item_name = '" + materailReq.getMaterial() + "'");
			}
			if (!StringUtils.isEmpty(materailReq.getPo())) {
				buff.append(" AND cs_po = '" + materailReq.getPo() + "'");
			}
			if (!StringUtils.isEmpty(materailReq.getErpOrder())) {
				buff.append(" AND po_number = '" + materailReq.getErpOrder() + "'");
			}

			logger.info("查询sql===========" + buff.toString());
			Query query = entityManager.createNativeQuery(buff.toString(), MaterialDetailEntity.class);
			list = query.getResultList();
		
			if (list != null && list.size() > 0) {
				BigDecimal totalAmountTax = BigDecimal.ZERO;
				for (MaterialDetailEntity material : list) {
					totalAmountTax = totalAmountTax.add(material.getAmountTax());
				}
				list.get(0).setTotalAmountTax(totalAmountTax);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
